# -*-coding: utf-8 -*-
"""
    @Theme   : 下载 A 股上市公司财报、爬取历史分红
    @Time    : 2024/3/20 14:13
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
import os
import sys

import click
import requests
import pandas as pd
from bs4 import BeautifulSoup

from .utils import format_thousandth

HOST = "basic.10jqka.com.cn"


def download_csv(file_type, code, download_dir):
    """从同花顺个股网下载资产负债表、利润表及现金流量表"""
    header = {
        "Connection": "keep-alive",
        "Host": HOST,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                      "Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
        "Referer": f"http://{HOST}/{code}/finance.html"
    }
    param = {
        "export": file_type,
        "type": "year",
        "code": code
    }

    url = f"http://{HOST}/api/stock/export.php"
    response = requests.session().get(url, params=param, headers=header)

    path = os.path.join(download_dir, f"{code}_{file_type}_year.xls")
    content = response.content

    if not content:
        click.echo(f'无法下载相应财报数据，请核对股票代码 {code} 是否正确!')
        sys.exit()
    else:
        with open(path, "wb") as f:
            f.write(content)


def download_bonus_payment(code, download_dir):
    """从同花顺个股网下载历史分红"""
    header = {
        "Connection": "keep-alive",
        "Host": HOST,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                      "Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
    }

    url = f"http://{HOST}/{code}/bonus.html#stockpage"

    response = requests.session().get(url, headers=header)
    content = response.content.decode('GBK')

    soup = BeautifulSoup(content, "html.parser")
    table = soup.find("table", {"id": "bonus_table"})
    if not table:
        click.echo(f'股票代码 {code} 的年度分红下载遇到问题，请在 correct.csv 中手动进行录入！')
        return

    columns = []
    for col in table.find_all("th"):
        col_name = col.text.strip()
        if col_name.endswith('分红总额'):
            col_name = '分红总额'
        columns.append(col_name)

    data = []
    for row in table.find_all("tr"):
        row_data = []
        for cell in row.find_all("td"):
            row_data.append(cell.text.strip())
        if row_data:
            data.append(row_data)

    df = pd.DataFrame(data=data, columns=columns)
    df = df[df['分红总额'] != '--']

    file = os.path.join(download_dir, 'bonus.csv')
    sub_df = pd.DataFrame(columns=['报告期', '分红总额'])
    if df.empty:
        sub_df.to_csv(file, index=False)
        return

    def _convert_to_year(date_str):
        return date_str[:4]

    def _convert_to_yuan(money):
        if money.endswith('亿'):
            return float(money[:-1]) * 100000000
        elif money.endswith('万'):
            return float(money[:-1]) * 10000

    sub_df['报告期'] = df['报告期'].apply(_convert_to_year)
    sub_df['分红总额'] = df['分红总额'].apply(_convert_to_yuan)

    sub_df = sub_df.groupby('报告期').sum()
    sub_df['分红总额'] = format_thousandth(sub_df['分红总额'])

    sub_df.to_csv(file)

